﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Transactions;

namespace Pg.BioMedics.SDR.Data.Strategy
{
    /// <summary>
    /// Manages transaction stored in Transaction.Current slot.
    /// </summary>
    internal class CurrentTransactionStrategy : ITransactionStrategy
    {
        #region ITransactionStrategy Members

        /// <summary>
        /// Gets transaction managed by this strategy
        /// </summary>
        public Transaction Transaction
        {
            get 
            {
                return Transaction.Current;
            }
        }

        /// <summary>
        /// Begins transaction managed by this strategy
        /// </summary>
        public void Begin()
        {
            if (Transaction.Current == null)
            {
                TransactionOptions options = new TransactionOptions();
                options.IsolationLevel = IsolationLevel.ReadCommitted;

                Transaction.Current = new CommittableTransaction(options);
            }
        }

        /// <summary>
        /// Margs transaction as completed
        /// </summary>
        public void Complete()
        {
            if (Transaction.Current != null)
            {
                CommittableTransaction transaction = Transaction.Current as CommittableTransaction;
                if (transaction != null)
                {
                    transaction.Commit();                    
                    Transaction.Current = null;

                    System.GC.Collect();
                    System.GC.WaitForPendingFinalizers();
                }
            }
        }

        /// <summary>
        /// Closes transaction managed by this strategy. If transaction hasn't been
        /// finizlied yet will be rolled back.
        /// </summary>
        public void Close()
        {
            if (Transaction.Current != null)
            {
                CommittableTransaction transaction = Transaction.Current as CommittableTransaction;
                if (transaction != null)
                {
                    transaction.Rollback();
                    Transaction.Current = null;

                    System.GC.Collect();
                    System.GC.WaitForPendingFinalizers();
                }
            }
        }

        #endregion
    }
}
